namespace Radar
{
    using System;
    using System.Threading;

    internal sealed class ThreadLocalLifetime : Lifetime
    {
        [ThreadStatic] private static ResolveContext context;

        protected override Func<ResolveContext, object> GetBuilderInternal(Func<ResolveContext, object> initialBuild)
        {
            var lockObject = new object();
            ThreadLocal<object> threadLocal = null;

            return c =>
                       {
                           context = c;

                           if (threadLocal == null)
                           {
                               lock (lockObject)
                               {
                                   if (threadLocal == null)
                                       threadLocal = new ThreadLocal<object>(() => initialBuild(context));
                               }
                           }

                           return threadLocal.Value;
                       };
        }
    }
}